package com.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * MyBatis的工具类
 */
public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //指定资源文件，配置文件mybatis-config.xml
            String resources = "mybatis-config.xml";
            //获取配置文件mybatis-config.xml对应的文件流InputStream
            InputStream resourceAsStream = Resources.getResourceAsStream(resources);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            System.out.println("sqlSessionFactory=" + sqlSessionFactory);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 编写方法，返回SqlSession对象-回话
     *
     * @return
     */
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }

}
